/**
 * 实现商品路由模块
 *    功能:
 *        1. 显示商品列表, /goods/list
 *           [
 *              {id:1001,name:'回锅肉',price:12.89,num:2},
 *              {id:1002,name:'鱼香肉丝',price:10.58,num:1},
 *              {id:1003,name:'红烧排骨',price:18.54,num:2},
 *           ]
 *        2. 添加商品 /goods/add
 *        3. 删除商品,根据商品ID删除商品
 *
 */
const express = require('express')
const goodsRouter = express.Router()

const goods = [
	{ id: 1001, name: '回锅肉', price: 12.89, num: 2 ,url:'https://image4.suning.cn/uimg/b2c/newcatentries/0000000000-000000000178605073_1_800x800.jpg'},
	{ id: 1002, name: '鱼香肉丝', price: 10.58, num: 1 ,url:'https://image5.suning.cn/uimg/b2c/newcatentries/0070066196-000000000682437966_1_800x800.jpg'},
	{ id: 1003, name: '红烧排骨', price: 18.54, num: 2 ,url:'https://image5.suning.cn/uimg/b2c/newcatentries/0070066196-000000000682437966_1_800x800.jpg'},
]
/**
 * 添加商品
 */
goodsRouter.get('/goods/add', (req, res) => {
    // 请求参数
	const id = req.query.id
	const name = req.query.name
	const price = req.query.price
	const num = req.query.num

    // 商品对象
	const item = { id: id, name: name, price: price, num: num }

	goods.push(item) // 添加商品到商品数组

    // 响应
	res.send({
		code: 1,
		message: '添加成功'
	})
})

/**
 * 删除商品
 */
goodsRouter.get('/goods/delete', (req, res) => {
	// 接收商品ID
    const id = req.query.id
    // 根据ID查找索引号
	const index = goods.findIndex(item => item.id == id)
    // 删除索引号对应元素
	goods.splice(index, 1)
    // 响应数据
	res.send({
		code: 1,
		message: '删除成功!'
	})
})

/**
 * 商品列表
 */
goodsRouter.get('/goods/list',(req,res)=>{
    // 响应商品列表
    res.send({
        code:1,
        list:goods
    })
})
module.exports = { goodsRouter }
